const User = require('../models/User');
const {decrypt} = require("../utils/utils");
const {sendToken} = require('../utils/sendToken')

// 用户登录
exports.login = async (req, res, next) => {
  //生成token
  const user = req.user
  const token = await sendToken(user)
  res.send({
    code: 20000,
    message: '登录成功',
    data: {
      userId: user._id,
      token: token
    }
  })
}

//注册
exports.register = async (req, res, next) => {
  try {
    let user = await User.create(req.body)
    //生成token
    let token = await sendToken(user)
    res.send({
      code: 20000,
      message: '注册成功',
      data: {
        userId: user._id,
        token: token
      }
    })
  } catch (err) {
    console.log(err)
    next(err)
  }
}

//获取单个用户信息

exports.userinfo = async (req, res, next) => {
  let _id = req._id
  try {
    let userResult = await User.findById(_id)
    userResult = userResult.toJSON()
    res.send({
      code: 20000,
      message: '查询成功',
      data: userResult
    })
  } catch (err) {
    console.log(err)
    next(err)
  }
}

//获取用户列表

exports.userList = async (req, res, next) => {
  const pageNumber = req.query.pageNumber ? parseInt(req.query.pageNumber) : 1
  const pageSize = req.query.pageSize ? parseInt(req.query.pageSize) : 3
  const filter = {}
  if (req.query.username) {
    filter.username = {$regex: req.query.username}
  }
  if (req.query.email) {
    filter.email = {$regex: req.query.email}
  }
  if (req.query.roles) {
    var arr = []
    arr.push(req.query.roles)
    filter.roles = arr
  }
  try {
    let total = await User.find(filter).count()
    let result = await User.find(filter).sort({'updatedAt': -1}).skip((pageNumber - 1) * pageSize).limit(pageSize)
    result = result.map(item => {
      return {
        _id: item._id,
        username: item.username,
        email: item.email,
        roles: item.roles.toString(),
        updatedAt: item.updatedAt
      }
    })
    res.json({
      code: 20000,
      data: result,
      pagination: {
        total,
        pageSize,
        pageNumber
      }
    })
  } catch (err) {
    next(err)
  }
}

//改变角色
exports.changeRole = async (req, res, next) => {
  const _id = req.body.id
  const roles = [req.body.roles]
  var json = {roles: roles, updatedAt: Date.now()}
  try {
    let data = await User.findByIdAndUpdate(_id, json)
    data.roles = roles
    res.json({
      code: 20000,
      data,
      message: '更新状态成功'
    })
  } catch (err) {
    next(err)
  }
}

